// =====================================================================
//
//  This file is part of the Microsoft Dynamics CRM SDK code samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//
// =====================================================================
#region

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.ServiceModel;
using System.ServiceModel.Channels;
using Microsoft.Xrm.Sdk.Client.Protocols.WSTrust;

#endregion

namespace Microsoft.Xrm.Sdk.Client
{
	public sealed class IssuerEndpoint
	{
		public TokenServiceCredentialType CredentialType { get; set; }
		public WSTrustConstants.Version TrustVersion { get; set; }

		public EndpointAddress IssuerAddress { get; set; }
		public Binding IssuerBinding { get; set; }
		public EndpointAddress IssuerMetadataAddress { get; set; }
	}

	public sealed class CrossRealmIssuerEndpointCollection : Dictionary<Uri, IssuerEndpointDictionary>
	{
		public CrossRealmIssuerEndpointCollection()
		{
		}

		[SuppressMessage("Microsoft.Design", "CA1043:UseIntegralOrStringArgumentForIndexers", Scope = "member")]
		public new IssuerEndpointDictionary this[Uri key]
		{
			get
			{
				if (base.ContainsKey(key))
				{
					return base[key];
				}

				return null;
			}
			set { base[key] = value; }
		}

	}

	public sealed class IssuerEndpointDictionary : Dictionary<String, IssuerEndpoint>
	{
		public IssuerEndpointDictionary()
		{
		}

		public IssuerEndpoint GetIssuerEndpoint(TokenServiceCredentialType credentialType)
		{
			if (credentialType == TokenServiceCredentialType.None)
			{
				return null;
			}

			foreach (KeyValuePair<string, IssuerEndpoint> issuer in this)
			{
				if (issuer.Value.CredentialType == credentialType)
				{
					return issuer.Value;
				}
			}
			throw new NotSupportedException(String.Format(CultureInfo.InvariantCulture,
														  "The authentication endpoint {0} was not found on the configured Secure Token Service!",
														  credentialType));
		}
	}

	public enum TokenServiceCredentialType
	{
		None = 0,
		[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")]
		Username = 1,
		Kerberos = 2,
		SymmetricToken = 3,
		AsymmetricToken = 4,
		Certificate = 5,
		Windows = 6,
		Bearer = 7,
	}
}
